package com.lau.dicttranslator.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring上下文持有者
 * 用于在非Spring管理的类中获取Spring Bean
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
    
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }
    
    /**
     * 获取ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }
    
    /**
     * 根据Bean名称获取Bean
     */
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) getApplicationContext().getBean(name);
    }
    
    /**
     * 根据Bean类型获取Bean
     */
    public static <T> T getBean(Class<T> clazz) {
        assertContextInjected();
        return getApplicationContext().getBean(clazz);
    }
    
    /**
     * 根据Bean名称和类型获取Bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        assertContextInjected();
        return getApplicationContext().getBean(name, clazz);
    }
    
    /**
     * 检查ApplicationContext是否已注入
     */
    private static void assertContextInjected() {
        if (applicationContext == null) {
            throw new IllegalStateException("ApplicationContext未注入，请确保SpringContextHolder已被Spring扫描注册");
        }
    }
    
    /**
     * 清理ApplicationContext
     */
    public static void clear() {
        applicationContext = null;
    }
} 